package com.malty.apimanage.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.malty.apimanage.domain.dto.*;
import com.malty.apimanage.domain.dto.api.ApiAddReq;
import com.malty.apimanage.domain.dto.api.ApiQueryReq;
import com.malty.apimanage.domain.dto.api.ApiUpdateReq;
import com.malty.apimanage.domain.vo.ApiMetaDataVO;
import com.malty.apimanage.service.ApiMetaDataService;
import com.malty.common.ErrorCode;
import com.malty.common.domain.Result;
import com.malty.common.exception.BusinessException;
import com.malty.common.util.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author malty
 */
@Api(tags = "API元数据管理")
@RestController
@RequestMapping("/api/manage")
public class ApiMetaDataController {
    @Resource
    private ApiMetaDataService apiMetaDataService;

    @ApiOperation("创建API信息")
    @PostMapping("/add")
    public Result<Boolean> addApi(@RequestBody ApiAddReq apiAddReq) {
        apiMetaDataService.saveApiMetaData(apiAddReq);
        return ResultUtils.success(true);
    }

    @ApiOperation("删除API信息")
    @PostMapping("/delete")
    public Result<Boolean> deleteApi(@RequestBody DeleteRequest deleteRequest) {
        return ResultUtils.success(apiMetaDataService.removeById(deleteRequest.getId()));
    }

    @ApiOperation("更新API信息")
    @PostMapping("/update")
    public Result<Boolean> updateApi(@RequestBody ApiUpdateReq apiUpdateRequest) {
        return ResultUtils.success(apiMetaDataService.updateApiMetaDataById(apiUpdateRequest));
    }

    @ApiOperation("根据id查询API信息")
    @GetMapping("/get")
    public Result<ApiMetaDataVO> getApiById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(apiMetaDataService.getApiMetaDataById(id));
    }

    @ApiOperation("根据条件API信息")
    @GetMapping("/list")
    public Result<List<ApiMetaDataVO>> listApi(ApiQueryReq apiQueryReq) {
        return ResultUtils.success(apiMetaDataService.listApiMetaDataByQuery(apiQueryReq));
    }


    @ApiOperation("根据条件分页查询API信息")
    @GetMapping("/list/page")
    public Result<Page<ApiMetaDataVO>> listApiByPage(ApiQueryReq apiQueryReq) {
        return ResultUtils.success(apiMetaDataService.pageList(apiQueryReq));
    }

    @ApiOperation("接口发布")
    @GetMapping("/online")
    public Result<Boolean> apiPublish(Long id) {
        return ResultUtils.success(apiMetaDataService.apiOnline(id));
    }

    @ApiOperation("接口下线")
    @GetMapping("/offline")
    public Result<Boolean> apiOffline(Long id) {
        return ResultUtils.success(apiMetaDataService.apiOffline(id));
    }
}
